const superagent = require('superagent');
const urllib = require('url');
const cheerio=require('cheerio');
const fs = require("fs");

//找到该连接下的所有图片
superagent.get("https://www.uc123.com/").end(function (err, res) {
	if(err){
		console.log(err)
	}
	 let $ = cheerio.load(res.text);
	 let $search = $("img");
	 let len = $search.length,i=1;
	 console.log(len)
  	 $search.each(function(){
		let url =$(this).attr("src");
		if(url){
			let json = urllib.parse(url);
			let filename ="";
			if(json.path.lastIndexOf("?")==-1){
				filename = json.path.substring(json.path.lastIndexOf("/")+1)
			}else{
				filename = json.path.substring(json.path.lastIndexOf("/")+1,json.path.lastIndexOf("?"))
			}
			if(json.protocol==null){
				url="https:"+url;
			}
			superagent.get(url).end(function (err, res) {
				if(err){
					console.log(err)
					console.log(`${filename}写入失败...(${i++}|${len})+${url}`)
				}
				if(res&&res.body){
					fs.writeFile("./img/"+filename,res.body,null,err=>{
						console.log(`${filename}写入成功...(${i++}|${len})`)
					})
				}
			})
		}
	})
})
